package com.itic.appbase.applications.exports.ExportExcelWithZip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itic.appbase.framework.utils.PropertyGetter;




/**
 * 导出到zip
 * Company: ITIC
 * @author  徐静
 * @date 2014年12月8日  下午1:39:05
 * @version 1.0
 */
public class ExportToZipUtils {
	private static final Logger log = LoggerFactory.getLogger(ExportToZipUtils.class);
	
	/**
	 * 压缩文件到zip并导出
	 * @param Map<String,Map<String,List<?>>> key为bzmc，value中的key为导出的excel文件名，list为导出的数据list
	 * @param dataList
	 * @param fileRootList
	 * @param request
	 * @param response void
	 */
	public static void ExportToZipUtil (Map<String,Map<String,List<?>>> map,List<String> filePathList,Map<String, String> keyMap,HttpServletRequest request, HttpServletResponse response) {
		try {
			Date date = new Date();
			long time = date.getTime();
			String root = getExportZipRootDir() + time + "/";
			String rootDir = root + time + "/"; //导入excel的文件夹
			String zipDir = root + time ;
			String zipFileFolder = rootDir + "attachment/"; //导入附件信息的文件夹
			//导出数据到excel并保存数据到指定临时文件夹,name为文件名，list为导出数据
			for (String bzmc : map.keySet()) {
				Map<String, List<?>> mapTemp = map.get(bzmc);
				for (String name : mapTemp.keySet()) {
					ExportExcelUtils.exportExcelToZipUtil(bzmc, mapTemp.get(name), rootDir, name, request);
				}
			}
			//将文件拷贝到临时文件夹中
			copyFileToTemporary(zipFileFolder, filePathList, keyMap);
			//压缩文件到rootDir中的zip中
			ZipUtils.zip(zipDir, zipDir + ".zip");
			//客户端下载
			downloadToClient(zipDir + ".zip", response);
			//删除生成的临时文件
			deleteTemporaryFile(root);
		} catch (Exception e) {
			log.error("[ExportToZipUtils | ExportToZipUtil]方法：", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 客户端下载
	 * @param string 
	 * @throws IOException 
	 */
	private static void downloadToClient(String filePath, HttpServletResponse response ) throws IOException {
		InputStream fis = null;
		OutputStream out = null;
		if (StringUtils.isNotBlank(filePath)) {
			try {
				//欲下载的文件的路径。
				File file = new File(filePath);
				// 取得文件名。
				String fileName = file.getName();
				// 以流的形式下载文件。
				fis = new BufferedInputStream(new FileInputStream(file));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				
				// 清空response
				response.reset();
				// 设置下载文件的类型
				response.setContentType("application/octet-stream");
				String newpath = new String(fileName.getBytes("utf-8"),"ISO-8859-1");
				response.setHeader("Content-Disposition", "attachment;filename=\"" + newpath + "\"");
				out = new BufferedOutputStream(response.getOutputStream());
				out.write(buffer);
			} catch (IOException e) {
				log.error("[ExportToZipUtils | downloadToClient]方法：", e);
				throw new RuntimeException(e);
			} finally {
				if (fis != null) {
					fis.close();
				}
				if (out != null) {
					out.flush();
					out.close();
				}
			}
		}
	}
	
	private static void deleteTemporaryFile(String zipDir) {
		try {
			org.apache.commons.io.FileUtils.deleteDirectory(new File(zipDir));
		} catch (IOException e) {
			log.info("删除临时文件失败");
			throw new RuntimeException("删除文件", e);
		}
	}

	/**
	 * 将文件拷贝到临时文件夹里面--救灾专家模块专用（keyMap）
	 * @param tempDir  临时文件根路径
	 * @param filePathList 文件路径
	 */
	private static void copyFileToTemporary(String tempDir, List<String> filePathList, Map<String,String> keyMap) {
		log.info("拷贝文件到zip开始");
		if (filePathList != null && filePathList.size() > 0) {
			for (String path : filePathList) {
				//path = fileNameWithMd5(path); //文件进行md5加密
				File sourceFile = new File(FileUtils.getRootPath(), path); //上传文件的路径
				if (sourceFile.exists()) {
					String tempPath = tempDir + path.substring(0, path.lastIndexOf("/")); //临时文件路径
					File tempFilePath = new File(tempPath);
					File tempFile = new File(tempDir, path);
				    if (!tempFilePath.exists()) {
						tempFilePath.mkdirs();
					} 
				   FileUtils.copy(sourceFile, tempFile);
				   
				   /*
				    * 更换文件名
				    */
				   String keyParam = "";
				
				   @SuppressWarnings("rawtypes")
				   Iterator keys = keyMap.keySet().iterator();
				   while(keys.hasNext()){
					   String key = (String)keys.next();
					   if(path.equals(keyMap.get(key))){
						   keyParam = key;
					   }
    			   }
				   
				   String c = tempFile.getParent();
				   String newName = c + File.separator + keyParam + path.substring(path.lastIndexOf("."));
				   tempFile.renameTo(new File(newName));
				}
			}
		}
		log.info("拷贝文件到zip结束");
	}
	
	/**
	 * 获取导出文件的临时路径 
	 * @return String
	 */
	private static String getExportZipRootDir() {
		// 获取用户目录
        String absolutePath = System.getProperties().getProperty("user.home");
        String dirName = PropertyGetter.getString("app.code");
        String rootDir = "/" + dirName + "_temporary";
        //创建fileupload文件夹
        File root = new File(absolutePath + rootDir);
        if(!root.exists()) {
			root.mkdir();
		}
        return absolutePath + rootDir + "/" ;
	}
	
//	private static String fileNameWithMd5(String filePath) {
//		String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
//		String prefix = fileName.substring(0,fileName.lastIndexOf("."));
//		String suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
//		String newFileName = MD5Util.md5(prefix) + suffix;
//		String path = filePath.substring(0, filePath.lastIndexOf("/")+1) + newFileName;
//		return path;
//	}

}
